
use anyhow::Result;
use hyper::{Client, client::HttpConnector};
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::rpc::{JsonRpcRequest, jsonrpc_request};
use crate::miner::types::TaskType;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct WorkerResource {
    pub mem_physical: u64,
    pub mem_swap: u64,
    pub mem_used: u64,
    pub mem_swap_used: u64,
    #[serde(rename(deserialize = "CPUs"))]
    pub cpus: u32,
    #[serde(rename(deserialize = "GPUs"))]
    pub gpus: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct WorkerInfo {
    pub hostname: String,
    pub ignore_resources: bool,
    pub resources: WorkerResource,
    pub work_limit: Option<HashMap<TaskType, u32>>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SealWorkerStats {
    pub info: WorkerInfo,
    pub enabled: bool,
    pub mem_used_min: u64,
    pub mem_used_max: u64,
    pub gpu_used: f64,
    pub cpu_use: u32,
}

pub async fn query_worker_from_miner(client: &Client<HttpConnector>, url: &str, token: &str) -> Result<HashMap<String, SealWorkerStats>>{
    let req = JsonRpcRequest::with_params("Filecoin.WorkerStats", vec![]);
    let r = jsonrpc_request::<HashMap<String, SealWorkerStats>>(client, url, token, req).await?;
    match r {
        None => Err(anyhow::anyhow!("no worker found.")),
        Some(v) => Ok(v),
    }
}